/**
 * app Easyui - 扩展
 *
 * Dependencies: app.js
 *
 */
// Easyui样式初始化
$.fn.tabs.defaults.tabHeight = 32; // tab标签条高度
$.fn.linkbutton.defaults.height = 32; // 按钮高度
$.fn.menu.defaults.itemHeight = 28; // menu高度

$.fn.validatebox.defaults.height = 32;
$.fn.textbox.defaults.height = 32;
$.fn.textbox.defaults.iconWidth = 24;
$.fn.datebox.defaults.height = 32;
$.fn.numberspinner.defaults.height = 32;
$.fn.timespinner.defaults.height = 32;
$.fn.numberbox.defaults.height = 32;
$.fn.combobox.defaults.height = 32;
$.fn.passwordbox.defaults.height = 32;
$.fn.filebox.defaults.height = 32;

$.fn.menu.defaults.noline = true;
$.fn.progressbar.defaults.height = 18; // 进度条


$.fn.combobox.defaults.editable = false;
$.fn.combobox.defaults.panelHeight = 'auto';

// datagrid
$.extend($.fn.datagrid.defaults, {
    method: 'get',
    striped: true,
    singleSelect: true,
    rownumbers: true,
    pagination: true,
    pageSize: 10,
    pageList: [10, 20, 50],
    loadFilter: function (data) {
        if (data.data) {
            return data.data;
        } else {
            return data;
        }
    }
});
// $.fn.datagrid.defaults.method = 'get';
// $.fn.datagrid.defaults.striped = true;
// $.fn.datagrid.defaults.singleSelect = true;
// $.fn.datagrid.defaults.rownumbers = true;
// $.fn.datagrid.defaults.pagination = true;
// $.fn.datagrid.defaults.pageSize = 10;
// $.fn.datagrid.defaults.pageList = [10, 20, 50];
// $.fn.datagrid.defaults.loadFilter = function (data) {
//     if (data.data) {
//         return data.data;
//     } else {
//         return data;
//     }
// };

$.fn.tree.defaults.method = 'get';
$.fn.treegrid.defaults.method = 'get';
$.fn.treegrid.defaults.pagination = false;

/**
 * 向combobox data中添加全部或请选择信息。信息默认为{text: '', value: ''}，且添加到顶部
 * @param data
 * @returns {Array}
 */
function e_combobox_addall_filter(data) {
    var newdata = [];
    if (data) {
        $.each(data, function (i, n) {
            newdata.push(n);
        });
        newdata.unshift({text: '', value: ''});
    }
    return newdata;
}

/**
 * 向tree data中添加全部或请选择信息。信息默认为{id: '', text: ''}
 * @param data
 * @param all
 * @returns {Array}
 */
function e_tree_addall_filter(data, all) {
    var newdata = [];
    if (data) {
        if (!all) {
            all = {id: '', text: ''};
        }
        // all.selected = true;
        all.children = data;
        newdata = [all]
    }
    return newdata;
}

/**
 * 把后台返回的tree grid结构处理成easyui tree可用的结构
 * @param treeGrid
 * @param idProp
 * @param nameProp
 * @param childrenProp
 * @returns {Array}
 */
function changeTreeGrid2TreeData(treeGrid, idProp, nameProp, childrenProp) {
    var treeData = [];
    $.each(treeGrid, function (i, d) {
        var node = {
            'id': d[idProp],
            'text': d[nameProp],
            'attributes': {}
        };
        for (var prop in d) {
            if (prop !== childrenProp) {
                node.attributes[prop] = d[prop];
            }
        }
        var children = d[childrenProp];
        if (children && children.length > 0) {
            node.state = 'open';
            node.children = changeTreeGrid2TreeData(children, idProp, nameProp, childrenProp);
        }
        treeData.push(node);
    });
    return treeData;
}

/**
 * 把后台返回的list结构处理成可用的key-value Map
 * @param list
 * @param keyProp
 * @returns {{}}
 */
function changeListData2Map(list, keyProp) {
    var map = {};
    $.each(list, function (i, d) {
        map[d[keyProp]] = d;
    });
    return map;
}

/**
 * 把后台返回的tree list结构处理成可用的key-value Map
 * @param list
 * @param idProp
 * @param nameProp
 * @param childrenProp
 * @param map
 */
function changeTreeGrid2Map(list, idProp, nameProp, childrenProp, map) {
    $.each(list, function (i, d) {
        map[d[idProp]] = d;
        var children = d[childrenProp];
        if (children && children.length > 0) {
            changeTreeGrid2Map(children, idProp, nameProp, childrenProp, map);
        }
    });
    return map;
}

function ajaxDict(types, callback) {
    return $.ajax({
        type: 'GET',
        url: CTX + '/sys/dict/findListByTypes',
        data: {
            types: types.join(',')
        },
        dataType: 'json',
        success: function (data) {
            data = $.dataFilter(data);
            if (data) {
                var dicts = data;
                var dict = {}, type = '';
                dict._list = {};
                $.each(dicts, function (i, d) {
                    type = d.type;
                    if (!dict[type]) {
                        dict[type] = {};
                        dict._list[type] = [];
                    }
                    dict[type][d.value] = d;
                    dict._list[type].push(d);
                });
                if (callback) {
                    callback(dict);
                }
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            $.dealResultData(XMLHttpRequest.responseJSON);
        }
    });
}


// ajaxDict(['status', 'role_type'], function (dict) {
//     statusMap = dict['status'];
//     typeMap = dict['role_type'];
//
//     statusList = dict._list['status'];
//     typeList = dict._list['role_type'];
//
//     $('#sf_status').combobox({
//         data: statusList,
//         value: 1,
//         loadFilter: e_combobox_addall_filter
//     });
//
//     initRoleGrid();
//
//     $('#fm_type').combobox({
//         data: typeList,
//         value: 2
//     });
//
//     $('#fm_status').combobox({
//         data: statusList,
//         value: 1
//     });
// });

/**
 * ajax 请求枚举数据
 * @param enumClassName enumClassName
 * @param callback callback
 * @returns {*}
 */
function ajaxEnum(enumClassName, callback) {
    return $.ajax({
        type: 'GET',
        url: CTX + '/sys/enum/' + enumClassName,
        dataType: 'json'
    })
        .done(function (data) {
            data = $.dataFilter(data);
            if (data) {
                var dict = {
                    _map: {},
                    _list: []
                };
                for (var p in data) {
                    data[p] === 0 ? data[p] == '0' : '';
                    dict._map[data[p]] = p;
                    dict._list.push({
                        text: p,
                        value: data[p]
                    });
                }
                if (callback) {
                    callback(dict);
                }
            }
        });
}

/*
 * ============================================================
 * 初始化基本的页面布局
 * ============================================================
 */
function initPage(DOMs, Req, gridOpts, funcQueryParams, autoLoad) {
    funcQueryParams = funcQueryParams || $.noop();

    var $dataGrid = DOMs.$dataGrid;

    gridOpts.method = Req.list.method;
    gridOpts.url = Req.list.url;
    gridOpts.queryParams = funcQueryParams();
    initDataGrid($dataGrid, gridOpts, autoLoad, DOMs.$contextMenu);
    addExportBtn($dataGrid, Req.export, funcQueryParams);

    // 查询
    DOMs.$searchBtn.click(function () {
        var params = funcQueryParams();
        var opts = $dataGrid.datagrid('options');
        if (!opts.url) {
            $dataGrid.datagrid('options').url = $dataGrid.data("_url_");
        }
        $dataGrid.datagrid('load', params);
    });
    // 重置
    DOMs.$resetBtn.click(function () {
        DOMs.$searchForm.form('reset');
        DOMs.$searchBtn.trigger('click');
    });
    // 按键
    $(document).keyup(function (event) {
        if (event.keyCode == 13) {//keyCode=13是回车键
            DOMs.$searchBtn.trigger('click');
        }
    });
}

/*
 * ============================================================
 * 初始化dataGrid
 * ============================================================
 */
function initDataGrid($dataGrid, gridOpts, autoLoad, $gridContextMenu) {
    gridOpts = $.extend({
        fit: true,
        loadFilter: function (data) {
            if (data.data) {
                return data.data;
            } else {
                return data;
            }
        },
        onHeaderContextMenu: function (e) {
            e.preventDefault();
            buildHeaderContextMenu(this).menu('show', {
                left: e.pageX,
                top: e.pageY
            });
        }
    }, gridOpts);

    if ($gridContextMenu) {
        gridOpts.onRowContextMenu = function (e, i) {
            e.preventDefault();
            $(this).datagrid('selectRow', i);
            $gridContextMenu.menu('show', {
                left: e.pageX,
                top: e.pageY
            });
        }
    }

    var columns = [];
    // 多选，不是复杂表头
    if (!gridOpts.singleSelect && gridOpts.columns.length === 1) {
        columns.push({
            field: '_ckx_',
            checkbox: true
        });
    }
    columns = columns.concat(gridOpts.columns[0]);
    gridOpts.columns = [columns];

    // 是否自动加载数据
    if (!autoLoad) {
        $dataGrid.data("_url_", gridOpts.url);
        gridOpts.url = null;
    }

    // 初始化数据表格
    $dataGrid.datagrid(gridOpts);
}

/*
 * ============================================================
 * 添加导出按钮到dataGrid
 * ============================================================
 */
function addExportBtn($dataGrid, exportReq, funcQueryParams) {
    var pager = $dataGrid.datagrid('getPager');
    var options = pager.pagination('options');
    var buttons = options.buttons || [];

    var expBtn = {
        text: '导出',
        iconCls: 'fa fa-file-excel-o',
        handler: function () {
            var params = funcQueryParams();
            var options = $dataGrid.datagrid('options');
            params.sort = options.sortName;
            params.order = options.sortOrder;
            params.filename = (options.title || '') + '导出信息.xls';
            $.showProgress();
            $.ajax({
                url: exportReq.url,
                type: exportReq.method,
                data: params,
                dataType: "json"
            }).done(function (data, textStatus, jqXHR) {
                $.dealResultData(data, function (fileDest) {
                    $.app.downloadFile(params.filename, fileDest);
                });
            }).always(function () {
                $.closeProgress();
            });
        }
    };
    buttons.push(expBtn);
    pager.pagination({
        buttons: buttons
    });
}

/*
 * ============================================================
 * 构建dataGrid Header上下文
 * ============================================================
 */
function buildHeaderContextMenu(target) {
    var $dataGrid = $(target);
    var state = $dataGrid.data('datagrid');
    if (!state.columnMenu) {
        state.columnMenu = $('<div></div>').appendTo('body');
        state.columnMenu.menu({
            onClick: function (item) {
                if (item.iconCls === 'tree-checkbox1') {
                    $dataGrid.datagrid('hideColumn', item.name);
                    $(this).menu('setIcon', {
                        target: item.target,
                        iconCls: 'tree-checkbox0'
                    });
                } else {
                    $dataGrid.datagrid('showColumn', item.name);
                    $(this).menu('setIcon', {
                        target: item.target,
                        iconCls: 'tree-checkbox1'
                    });
                }
            }
        });
        var fields = $dataGrid.datagrid('getColumnFields', true).concat($dataGrid.datagrid('getColumnFields', false));
        for (var i = 0; i < fields.length; i++) {
            var field = fields[i];
            var col = $dataGrid.datagrid('getColumnOption', field);
            if (col.hidden) {
                continue;
            }
            state.columnMenu.menu('appendItem', {
                text: col.title,
                name: field,
                iconCls: 'tree-checkbox1'
            });
        }
    }
    return state.columnMenu;
}

/*
 * ============================================================
 * 重新刷新easyui布局结构下各模块的高度
 * ============================================================
 */
function setHeight($ly) {
    // get the north panel
    var np = $ly.layout('panel', 'north');
    var oldHeight = np.panel('panel').outerHeight();
    np.panel('resize', {
        height: 'auto'
    });
    var newHeight = np.panel('panel').outerHeight();
    $ly.layout('resize', {
        height: ($ly.height() + newHeight - oldHeight)
    });
}

